﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CWB.Web.MVC.BaseController;
using CWB.Web.Models.Configuration;
using CWB.Common.Logging;
using CWB.Web.DB;
using CWB.Web.Configuration;
using CWB.Common.Constant;
using CWB.Web;
using CWB.Web.Models;
using CWB.Common.Utilities;
using CWB.Web.CacheLayer;

namespace CWB.WebSite.Controllers.Service
{
    public class LoginServiceController : MultiCultureBaseController
    {
        private static readonly ISysLog Log = SysLog.GetLogger(typeof(LoginServiceController));

        public LoginServiceController(LanguageInfo languageInfo)
            : base(languageInfo)
        {
            ControllerPermision = Permission.Public;
        }

        //
        // GET: /LoginService/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult BouLogin(string username, string password, string verify)
        {
            DbTableBbu o = new DbTableBbu();
            bool isLogined = false;
            ResultBase result = new ResultBase();
            Trading trading = sessionData.trading ?? new Trading();
            if (string.IsNullOrEmpty(trading.chk))
            {
                result.setException(Err.SessionTimeOutOrLost, "BouLogin");
            }
            try
            {
                if (AppConfigManager.SystemSetting.CaptchaCode && verify != (string)Session[SessionKeys.VerifyCode])
                {
                    result.Result = ReturnCode.CaptchaIncorrect;
                }
                else
                {
                    isLogined = o.VerifyBouLogin(username, password);

                    if (isLogined)
                    {
                        result.Result = ReturnCode.Success;

                        DbModuleBbu bbu = o.getBbuByName(username);
                        bbu.chk = Session.SessionID;
                        trading = new Trading()
                        {
                            chk = Session.SessionID,
                            isLogined = true,
                            languageInfo = LanguageInfo,
                            loginType = LoginType.Bo,
                            logoutUrl = "Login/BouLogin",
                            sn = bbu.sn,
                            userName = bbu.username,
                            position = 0
                        };
                        sessionData.trading = trading;
                        o.UpdateBouChk(bbu);
                        Log.Debug(string.Format("Bou [{0}] isLogined : {1}", username, isLogined.ToString()));
                    }
                    else
                    {
                        Log.Debug(string.Format("Bou [{0}] isLogined : {1}", username, isLogined.ToString()));
                    }
                }
                result = getLoginResultMessage(result);
                return Json(result, JsonRequestBehavior.DenyGet);
            }
            catch(Exception ex)
            {
                return Json(ex.Message, JsonRequestBehavior.DenyGet);
            }
        }

        public JsonResult Logout()
        {
            if (sessionData != null && sessionData.trading != null)
            {
                switch (sessionData.trading.loginType)
                {
                    case LoginType.Agent:
                        DbTableAgent p = new DbTableAgent();
                        p.RemoveAgentChk(sessionData.trading.userName);
                        break;
                    case LoginType.Bo:
                        DbTableBbu o = new DbTableBbu();
                        o.RemoveBouChk(sessionData.trading.userName);
                        break;
                }
                sessionData.Logout();
            }
            ResultBase r = new ResultBase()
            {
                Message = Resources.Text.Logouted,
                Result = ReturnCode.Success
            };
            return Json(r, JsonRequestBehavior.AllowGet);
        }


        [HttpPost]
        public JsonResult AgentLogin(string username, string password, string verify)
        {
            DbTableAgent o = new DbTableAgent();
            bool isLogined = false;
            ResultBase result = new ResultBase();
            Trading trading = sessionData.trading ?? new Trading();
            if (string.IsNullOrEmpty(trading.chk))
            {
                result.setException(Err.SessionTimeOutOrLost, "AgentLogin");
            }
            try
            {
                if (AppConfigManager.SystemSetting.CaptchaCode && verify != (string)Session[SessionKeys.VerifyCode])
                {
                    result.Result = ReturnCode.CaptchaIncorrect;
                }
                else
                {
                    int agentSN = 0;
                    isLogined = o.VerifyAgentLogin(username, password, out agentSN);
                    if (isLogined)
                    {
                        DbModuleAgent dma = o.getAgentbySn(agentSN);
                        if (dma.Position < 3) // position 3 is member.
                        {
                            dma.chk = Session.SessionID;
                            trading = new Trading()
                            {
                                chk = Session.SessionID,
                                isLogined = true,
                                languageInfo = LanguageInfo,
                                loginType = LoginType.Agent,
                                logoutUrl = "",
                                sn = dma.sn,
                                userName = dma.Loginid,
                                position = dma.Position
                            };
                            sessionData.trading = trading;
                            o.UpdateAgentChk(dma);
                            result.Result = ReturnCode.Success;
                            Log.Debug(string.Format("Agent [{0}] isLogined success. return isLogined: {1}", username, isLogined.ToString()));
                        }
                        else
                        {
                            result.Result = ReturnCode.Failed;
                            Log.Debug(string.Format("Loginid({0}) is member, can't logined.", username));
                        }
                    }
                    else
                    {
                        result.Result = ReturnCode.Failed;
                        Log.Debug(string.Format("Agent [{0}] isLogined failed. return isLogined: {1}", username, isLogined.ToString()));
                    }
                }
                result = getLoginResultMessage(result);
                return Json(result, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                return Json(ex.Message, JsonRequestBehavior.DenyGet);
            }
        }

        private static ResultBase getLoginResultMessage(ResultBase lr)
        {
            switch (lr.Code)
            {
                case 1:
                    lr.Message = default(string);
                    break;
                case -9:
                    lr.Message = Localization.TranslateMessage(Err.CaptchaCodeCannotBeEmpty);
                    break;
                case -1:
                    lr.Message = Localization.TranslateMessage(Err.UserNameAndPasswordDoesnotMatch);
                    break;
                default:
                    lr.Message = string.Format("Return Code [{0}] not defined.", lr.Code);
                    break;
            }
            return lr;
        }
    }
}
